using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Web;
using UMC.Data.Entities;
using UMC.Web.UI;
using UMC.Proxy.Entities;
using UMC.Net;
using UMC.Data;
using System.Collections.Specialized;

namespace UMC.Proxy.Activities
{
    /// <summary>
    /// 邮箱账户
    /// </summary>
    [UMC.Web.Mapping("Proxy", "UMC", Auth = WebAuthType.Admin)]
    class SiteUMCActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var root = this.AsyncDialog("Root", r => this.Prompt("请传入站点"));
            var site = DataFactory.Instance().SiteConfig(root);
            var cfg = Reflection.Configuration("UMC");
            var nameKey = this.AsyncDialog("Key", r =>
            {
                if (site.Site.UserModel != UserModel.Bridge)
                {
                    this.Prompt("云模块需要桥接身份模式");
                }
                var ui = UISection.Create(new UITitle($"轻应用云模块"));
                ui.AddCell("所属应用", site.Caption);

                var ds = JSON.Deserialize(new Uri(site.Domains[0] + "/UMC/System/Setup/Mapping").WebRequest().Get().ReadAsString()) as Hashtable;
                var hash = new Dictionary<String, bool>();
                if (ds?.ContainsKey("data") == true)
                {
                    var data = ds["data"] as Array;
                    var ui2 = ui.NewSection();
                    ui2.Header.Put("text", $"{site.Caption}的云模块");
                    foreach (var o in data)
                    {
                        var dic = o as Hashtable;
                        if (dic.ContainsKey("model"))
                        {
                            var model = dic["model"] as string;
                            String key = "";
                            if (dic.ContainsKey("cmd"))
                            {
                                var cmd = dic["cmd"];
                                key = $"{model}.{cmd}";
                            }
                            else
                            {

                                key = $"{model}.*";
                            }
                            hash[key] = true;
                            var click = UIClick.Click(new UIClick(new WebMeta(request.Arguments).Put(r, key)).Post(request));
                            var p = cfg[key];
                            if (p != null)
                            {
                                if (String.Equals(p.Attributes["root"], site.Root))
                                {
                                    var cell = UICell.UI('\uea07', key, dic["desc"] as string, click);
                                    var item = cell.Data as WebMeta;
                                    item.Put("Color", "#09bb07");
                                    // cell.Style.Name("Icon").Color(0x09bb07);
                                    ui2.Add(cell);
                                }
                                else
                                {

                                    ui2.Add(UICell.UI('\uea07', key, dic["desc"] as string, click));
                                }
                            }
                            else
                            {
                                ui2.Add(UICell.UI('\uea01', key, dic["desc"] as string, click));
                            }
                        }
                    }
                }
                var u2 = ui.NewSection();
                u2.Header.Put("text", "云模块");
                foreach (var p in cfg.Providers)
                {
                    var croot = p.Attributes["root"];

                    if (String.Equals(croot, site.Root) == false)
                    {
                        if (hash.ContainsKey(p.Name) == false)
                        {
                            u2.AddCell(p.Name, croot, new UIClick(croot).Post(request.Model, request.Command));
                        }

                    }
                    else if (hash.ContainsKey(p.Name) == false)
                    {
                        u2.AddCell(p.Name, croot, new UIClick(p.Name).Post("System", "Web"));

                    }
                }
                if (u2.Length == 0)
                {
                    u2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有其他应用云模块").Put("icon", "\uF016"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),

                    new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));

                }
                ui.UIFootBar = new UIFootBar() { IsFixed = true };
                ui.UIFootBar.AddText(new UIEventText("配置云模块").Click(new UIClick(new WebMeta(request.Arguments).Put(r, "New")).Post(request)),
                    new UIEventText("检测配置").Click(new UIClick(new WebMeta(request.Arguments).Put(r, "Check")).Post(request)).Style(new UIStyle().BgColor()));


                ui.SendTo(this.Context, true, "System.Web", $"{request.Model}.{request.Command}");
            });
            switch (nameKey)
            {
                case "Check":
                    var ns = new NameValueCollection();
                    var time = Utility.TimeSpan();

                    var webItem = new WebMeta();
                    webItem.Put("time", time);
                    webItem.Put("appId", time);
                    ns.Add("appId", site.Root);
                    ns.Add("time", time.ToString());

                    webItem.Put("sign", Data.Utility.Sign(ns, site.Site.AppSecret));
                    var ls = JSON.Deserialize<WebMeta>(new Uri(site.Domains[0] + "/UMC.Conf").WebRequest().Put(webItem).ReadAsString());


                    switch (ls["code"] ?? "")
                    {
                        case "success":
                            this.Prompt("云模板效验通过");
                            break;
                        case "error":
                            this.Prompt("错误", "验证不通过");
                            break;
                        case "unactivated":
                            var conf = JSON.Deserialize<WebMeta>(new Uri(site.Domains[0] + "/UMC.Conf").WebRequest().Put(new WebMeta().Put("authSecret", site.Site.AppSecret).Put("domain", $"{site.Root}.{Web.WebResource.Instance().WebDomain()}")).ReadAsString());
                            if (String.Equals(conf?["code"], "success"))
                            {
                                this.Prompt("同步成功");
                            }
                            break;
                        default:
                            this.Prompt("提示", "请确认云模块是否正常开启");
                            break;
                    }

                    return;
                case "New":
                    var Settings = this.AsyncDialog("Settings", g =>
                    {
                        var fm = new UIFormDialog() { Title = "配置云模块" };

                        fm.AddText("模块名", "model", String.Empty);
                        fm.AddText("指令名", "cmd", String.Empty);
                        fm.AddText("描述", "desc", String.Empty);

                        fm.Submit("确认", $"{request.Model}.{request.Command}");
                        return fm;
                    });

                    nameKey = $"{Settings["model"]}.{Settings["cmd"]}";
                    var p2 = Data.Provider.Create(nameKey, "UMC");
                    p2.Attributes.Add("root", site.Root);
                    p2.Attributes.Add("desc", Settings["desc"]);

                    cfg.Add(p2);
                    Reflection.Configuration("UMC", cfg);
                    this.Context.Send(true);
                    break;
            }
            var item = new WebMeta();
            item.Put("Color", "#111");
            var p = cfg[nameKey];
            if (p != null)
            {


                if (p.Attributes["root"] != root)
                {
                    this.AsyncDialog("Confirm", r => new UIConfirmDialog("当前云模板并不是当前应用，你要替换嘛"));
                    item.Put("Icon", "\uea07").Put("Color", "#09bb07");
                    p.Attributes["root"] = root;
                }
                else
                {
                    item.Put("Icon", "\uea01");
                    cfg.Remove(nameKey);
                }
            }
            else
            {
                var provider = Provider.Create(nameKey, "UMC");
                provider.Attributes["root"] = root;
                cfg.Add(provider);

                item.Put("Icon", "\uea07").Put("Color", "#09bb07");
                // cell.Style.Name("Icon").Color(0x09bb07);

            }

            Reflection.Configuration("UMC", cfg);

            var ui = this.AsyncDialog("UI", g => this.DialogValue("none"));
            var section = this.AsyncDialog("section", g => this.DialogValue("1"));
            var row = this.AsyncDialog("row", g => this.DialogValue("1"));

            var editer = new Web.UISection.Editer(section, row);
            editer.Value(item);
            editer.Builder(this.Context, ui, true);
            // switch(k)

            //         }
        }
    }
}